<template>
  <div :class="cssPrefix">
    <div :class="`${cssPrefix}-detail`">
      <el-cascader
        :options="regionData"
        v-model="addressPrefix"
        placeholder="请选择 省/市/区"
        @change="updateMapAddress"
      >
      </el-cascader>
      <el-input
        v-model="addressDetail"
        placeholder="请输入街道/小区/乡镇/村等"
        @input="updateMapAddress"
      />
    </div>
    <div :class="`${cssPrefix}-map`">
      <hs-map v-model="_modelValue" ref="hsMapCom" />
    </div>
  </div>
</template>

<script setup>
import { computed, ref, watch } from 'vue'
import HsMap from '../Map/index.vue'
import { regionData } from 'element-china-area-data'
import _ from 'lodash'
const cssPrefix = 'hs-address'
const hsMapCom = ref()

const emit = defineEmits()
const props = defineProps({
  modelValue: {
    type: Object,
    default: () => ({
      address: '',
      lng: '',
      lat: '',
    }),
  },
})

let lng = ref(props.modelValue.lng)
let lat = ref(props.modelValue.lat)
let address = ref(props.modelValue.address)
const _lng = computed({
  get() {
    return lng.value
  },
  set(v) {
    lng.value = v
    updateModelValue()
  },
})
const _lat = computed({
  get() {
    return lat.value
  },
  set(v) {
    lat.value = v
    updateModelValue()
  },
})
const _address = computed({
  get() {
    return address.value
  },
  set(v) {
    address.value = v
    updateModelValue()
  },
})
const _modelValue = computed({
  get() {
    return {
      address: _address.value,
      lng: _lng.value,
      lat: _lat.value,
    }
  },
  set(v) {
    _address.value = v.address
    _lng.value = v.lng
    _lat.value = v.lat
  },
})

const updateModelValue = () => {
  emit('update:modelValue', {
    address: address.value,
    lng: lng.value,
    lat: lat.value,
  })
}

const addressPrefix = computed({
  get() {
    const [province, city, area] = _address.value.split('/')
    return [province, city, area]
  },
  set(val) {
    _address.value = val.join('/') + '/' + addressDetail.value
  },
})
const addressDetail = computed({
  get() {
    const [, , , ...detail] = _address.value.split('/')
    return detail.join(',')
  },
  set(val) {
    _address.value = addressPrefix.value.join('/') + '/' + val
  },
})

const updateMapAddress = _.debounce(() => {
  hsMapCom.value.updateAddress(_address.value)
}, 500)
</script>

<style lang="scss">
$prefix: 'hs-address';

.#{$prefix} {
  display: flex;
  flex-direction: column;
  width: 100%;
  &-detail {
    display: flex;
    > div:nth-of-type(n + 2) {
      margin-left: 10px;
    }
    > div {
      flex: 1;
    }
  }
  &-map {
    margin-top: 10px;
  }
}
</style>
